<template>
  <div class="step-one">
    <!-- 基本信息 -->
    <div class="basic-info">
      <div class="section-title">基本信息</div>
      <el-form :model="form" label-width="120px" label-position="left">
        <!-- 第一行：地区 -->
        <el-row :gutter="20" type="flex" justify="center">
          <el-col :span="12">
            <el-form-item label="地区">
              <el-select
                v-model="form.region"
                placeholder="请选择地区"
                size="small"
                style="width: 100%"
                :disabled="readonly"
                filterable
                @change="handleRegionChange"
              >
                <el-option
                  v-for="item in regionList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 第二行：项目名称&描述 -->
        <el-row :gutter="20" type="flex" justify="center">
          <el-col :span="12">
            <el-form-item label="项目名称&描述">
              <el-input
                v-model="form.projectName"
                type="textarea"
                resize="none"
                :rows="3"
                placeholder="请输入项目名称&描述 (最多100个字符)"
                :readonly="readonly"
                maxlength="100"
                show-word-limit
                @input="handleProjectNameChange"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 第三行：电价方案 -->
        <el-row :gutter="20" type="flex" justify="center">
          <el-col :span="12">
            <el-form-item label="电价方案">
              <el-select
                v-model="form.priceSchemeId"
                placeholder="请选择电价方案"
                size="small"
                style="width: 100%"
                :disabled="readonly"
                @change="handlePriceSchemeChange"
              >
                <el-option
                  v-for="item in priceSchemeList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 第四行：月份 -->
        <el-row :gutter="20" type="flex" justify="center">
          <el-col :span="12">
            <el-form-item label="月份">
              <el-select
                v-model="form.month"
                placeholder="请选择月份"
                size="small"
                style="width: 100%"
                :disabled="readonly"
                @change="handleMonthChange"
              >
                <el-option
                  v-for="item in monthList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 第五行：时间 -->
        <el-row :gutter="20" type="flex" justify="center">
          <el-col :span="12">
            <el-form-item label="时间">
              <el-input
                v-model="timeRange"
                placeholder="请先选择电价方案和月份"
                size="small"
                style="width: 100%"
                readonly
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 电价配置 -->
    <PriceConfig
      :price-config="form.priceConfig"
      :price-scheme-data="selectedPriceScheme"
      :selected-month="form.month ? Number(form.month) : null"
      @update:price-config="handlePriceConfigChange"
    />
  </div>
</template>

<script>
import PriceConfig from './PriceConfig.vue'
import { getElectricSchemeApi } from '@/api/Microgrid/EnergyStoragePlanning'
import { getDictionary1Api } from '@/api'

export default {
  name: 'StepOne',
  components: {
    PriceConfig
  },
  props: {
    formData: {
      type: Object,
      default: () => ({})
    },
    manageNo: {
      type: String,
      default: ''
    },
    readonly: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      form: {
        region: this.formData.region || '',
        projectName: this.formData.projectName || '',
        priceSchemeId: this.formData.priceSchemeId || '',
        month: this.formData.month || '',
        priceConfig: this.formData.priceConfig || {
          peak: { price: '0.00', timePeriods: [] },
          high: { price: '0.00', timePeriods: [] },
          flat: { price: '0.00', timePeriods: [] },
          offPeak: { price: '0.00', timePeriods: [] },
          superOffPeak: { price: '0.00', timePeriods: [] }
        }
      },
      regionList: [],
      priceSchemeList: [],
      selectedPriceScheme: null, // 当前选中的电价方案完整数据
      timeRange: '', // 时间范围显示
      monthList: [
        { label: '1月', value: 1 },
        { label: '2月', value: 2 },
        { label: '3月', value: 3 },
        { label: '4月', value: 4 },
        { label: '5月', value: 5 },
        { label: '6月', value: 6 },
        { label: '7月', value: 7 },
        { label: '8月', value: 8 },
        { label: '9月', value: 9 },
        { label: '10月', value: 10 },
        { label: '11月', value: 11 },
        { label: '12月', value: 12 }
      ]
    }
  },
  watch: {
    formData: {
      handler(newVal) {
        if (newVal) {
          this.form.region = newVal.region || ''
          this.form.projectName = newVal.projectName || ''
          this.form.priceSchemeId = newVal.priceSchemeId || ''
          this.form.month = newVal.month || ''
          this.form.priceConfig = newVal.priceConfig || {
            peak: { price: '0.00', timePeriods: [] },
            high: { price: '0.00', timePeriods: [] },
            flat: { price: '0.00', timePeriods: [] },
            offPeak: { price: '0.00', timePeriods: [] },
            superOffPeak: { price: '0.00', timePeriods: [] }
          }
          // 如果已有选中的方案和月份，更新时间范围
          this.$nextTick(() => {
            if (this.form.priceSchemeId && this.priceSchemeList.length > 0) {
              const selected = this.priceSchemeList.find(
                (item) => item.id === this.form.priceSchemeId
              )
              if (selected) {
                this.selectedPriceScheme = selected
                this.updateTimeRange()
              }
            }
          })
        }
      },
      deep: true,
      immediate: true
    },
    manageNo: {
      handler(newVal, oldVal) {
        // 只有当 manageNo 有值且发生变化时才调用接口
        if (newVal && newVal !== oldVal) {
          console.log('manageNo 变化，触发获取电价方案列表:', newVal)
          this.$nextTick(() => {
            this.getPriceSchemeList()
          })
        }
      },
      immediate: true
    }
  },
  async mounted() {
    // 获取地区列表
    await this.getRegionList()
    // 组件挂载时，如果 manageNo 已经有值则调用接口
    if (this.manageNo) {
      this.getPriceSchemeList()
    }
  },
  methods: {
    // 获取地区列表
    async getRegionList() {
      try {
        const res = await getDictionary1Api('CITY_CODE')
        if (res && res.code === 200 && res.data && res.data.list) {
          // 将字典数据映射为下拉框需要的格式
          this.regionList = res.data.list.map((item) => {
            return {
              label: item.text,
              value: item.value
            }
          })
        } else {
          console.warn('获取地区列表失败:', res)
          this.regionList = []
        }
      } catch (error) {
        console.error('获取地区列表失败:', error)
        this.regionList = []
      }
    },
    // 获取电价方案列表
    async getPriceSchemeList() {
      // manageNo 是必填参数，如果没有值则不调用接口
      if (!this.manageNo) {
        console.warn('manageNo 未设置，跳过获取电价方案列表')
        return
      }
      try {
        const params = {
          manageNo: this.manageNo
        }
        console.log('获取电价方案列表，参数:', params)
        const res = await getElectricSchemeApi(params)
        console.log('电价方案列表接口返回:', res)
        console.log('res.data 内容:', res?.data)
        console.log('res.data.list 内容:', res?.data?.list)
        console.log('res.data.entity 内容:', res?.data?.entity)

        if (res && res.code === 200 && res.data) {
          // 根据实际返回数据，list 数组中包含 templateId 和 templateName
          if (
            res.data.list &&
            Array.isArray(res.data.list) &&
            res.data.list.length > 0
          ) {
            // 保存完整的方案数据，包括 priceJson
            this.priceSchemeList = res.data.list.map((item) => {
              return {
                id: item.templateId,
                name: item.templateName,
                priceJson: item.priceJson // 保存完整的 priceJson 数据
              }
            })
            // 如果当前已选中方案，更新 selectedPriceScheme
            if (this.form.priceSchemeId) {
              const selected = this.priceSchemeList.find(
                (item) => item.id === this.form.priceSchemeId
              )
              if (selected) {
                this.selectedPriceScheme = selected
                this.updateTimeRange()
              }
            }
          } else {
            this.priceSchemeList = []
          }
          console.log('处理后的电价方案列表:', this.priceSchemeList)
        } else {
          console.warn('电价方案列表接口返回异常:', res)
          this.priceSchemeList = []
        }
      } catch (error) {
        console.error('获取电价方案列表失败:', error)
        this.priceSchemeList = []
      }
    },
    handleRegionChange(value) {
      this.updateFormData({ region: value })
    },
    handleProjectNameChange() {
      this.updateFormData({ projectName: this.form.projectName })
    },
    handlePriceSchemeChange(value) {
      this.updateFormData({ priceSchemeId: value })
      // 找到选中的方案并保存完整数据
      const selected = this.priceSchemeList.find((item) => item.id === value)
      if (selected) {
        this.selectedPriceScheme = selected
      } else {
        this.selectedPriceScheme = null
      }
      // 更新时间范围
      this.updateTimeRange()
    },
    handleMonthChange(value) {
      this.updateFormData({ month: value })
      // 更新时间范围
      this.updateTimeRange()
    },
    // 更新时间范围显示
    updateTimeRange() {
      if (!this.selectedPriceScheme || !this.form.month) {
        this.timeRange = ''
        return
      }

      try {
        // 解析 priceJson
        const priceJson = JSON.parse(this.selectedPriceScheme.priceJson)
        // 根据月份获取对应的数据，M1-M12 对应 1-12 月
        const monthKey = `M${this.form.month}`
        const monthData = priceJson[monthKey]

        if (monthData && Array.isArray(monthData) && monthData.length > 0) {
          // 获取第一个元素的 RQ 字段
          const rq = monthData[0].RQ
          if (rq) {
            // 将 "01-01,01-31" 格式转换为 "01-01~01-31"
            this.timeRange = rq.replace(',', '~')
          } else {
            this.timeRange = ''
          }
        } else {
          this.timeRange = ''
        }
      } catch (error) {
        console.error('解析 priceJson 失败:', error)
        this.timeRange = ''
      }
    },
    handlePriceConfigChange(value) {
      this.form.priceConfig = value
      this.updateFormData({ priceConfig: value })
    },
    updateFormData(data) {
      this.$emit('update:form-data', {
        ...this.formData,
        ...data
      })
    },
    // 验证表单：手动检查基本信息是否都有值
    validateForm() {
      // 检查地区
      if (!this.form.region || this.form.region.trim() === '') {
        this.$message.warning('请完善基本信息')
        return false
      }
      // 检查项目名称&描述
      if (!this.form.projectName || this.form.projectName.trim() === '') {
        this.$message.warning('请完善基本信息')
        return false
      }
      // 检查电价方案
      if (!this.form.priceSchemeId || this.form.priceSchemeId === '') {
        this.$message.warning('请完善基本信息')
        return false
      }
      // 检查月份
      if (!this.form.month || this.form.month === '') {
        this.$message.warning('请完善基本信息')
        return false
      }
      return true
    },
    // 获取第一步提交数据
    getSubmitData() {
      // 将时间范围格式从 "01-01~01-31" 转换回 "01-01,01-31"
      let electricPricePlanRange = this.timeRange || ''
      if (electricPricePlanRange) {
        electricPricePlanRange = electricPricePlanRange.replace('~', ',')
      }
      return {
        region: this.form.region,
        projectName: this.form.projectName,
        electricPricePlanId: this.form.priceSchemeId,
        electricPricePlanJson: this.selectedPriceScheme
          ? this.selectedPriceScheme.priceJson
          : '',
        electricPricePlanMonth: this.form.month
          ? Number(this.form.month)
          : null,
        electricPricePlanRange: electricPricePlanRange
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.step-one {
  .basic-info,
  .price-config {
    margin-bottom: 30px;
  }

  .section-title {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 20px;
  }
}
</style>
